package com.hkts.sinoiov.openapi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hkts.management.common.utils.BeanConvertUtils;
import com.hkts.management.common.utils.DateUtils;
import com.hkts.management.common.utils.SnowFlakeUtil;
import com.hkts.sinoiov.constants.CommonConstants;
import com.hkts.sinoiov.model.ApiHisTrack;
import com.hkts.sinoiov.model.ApiLocation;
import com.hkts.sinoiov.result.SinnoiovResult;
import com.hkts.sinoiov.sinoiovHisTrack.entity.SinoiovHisTrack;
import com.hkts.sinoiov.sinoiovHisTrack.service.ISinoiovHisTrackService;
import com.hkts.sinoiov.sinoiovLocation.entity.SinoiovLocation;
import com.hkts.sinoiov.sinoiovLocation.service.ISinoiovLocationService;
import com.hkts.sinoiov.sinoiovRecord.entity.SinoiovRecord;
import com.hkts.sinoiov.sinoiovRecord.service.ISinoiovRecordService;
import com.hkts.sinoiov.utils.GPSUtil;
import com.hkts.sinoiov.utils.ResultOpen;
import com.openapi.sdk.service.DataExchangeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Component
@Slf4j
@SuppressWarnings("unchecked")
public class OpenApi {
@Autowired
private RedisTemplate redisTemplate;

//    private static String USER="3d8f2d4a-1e7b-4c50-b5bf-9067b68c4d23";
//    private static String PWD="9983130q4vu00560X01s8696Q495Mg";
//    private static String STR="261469ca-151a-42ed-8597-7c19ffd00761";
//    private static String CID="19e7b941-ea53-4f5e-8f05-c915026a30cb";
//    private static String OPEN_URL="https://openapi-test.sinoiov.cn";
    private static String USER="268f9f99-461d-4296-b2ac-1b6de99aaa9e";
    private static String PWD="85kB0Zj88K58i59RwJy89Pb7Cv75k1";
    private static String STR="9783ac30-0779-4a28-9faa-ebcc2a86ec8e";
    private static String CID="2d5cb33f-c331-4966-a0de-d331f197275e";
    private static String OPEN_TOKEN="open_token";
    private static String OPEN_URL="https://zhiyunopenapi.95155.com";

    /** 用户登陆
     * 用户首次调用接口，须先登录，认证通过后生成令牌。
     令牌，多服务调用业务接口时，建议由统一服务调用登录接口将令牌缓存起来，多个服务统一从
     共享缓存中获取令牌。
     为安全考虑，建议用户自己每月至少更新一次令牌。
     令牌失效后再调用登录接口获取令牌，避免频繁调用登录接口，建议一天内登录次数不超过 10
     次，超过 10 次将触发安全系统报警。
     * */
    public String  login() {
        Object  token=redisTemplate.opsForValue().get(OPEN_TOKEN);
        if(token==null){
            try {
                Map<String, String> map = new HashMap<String, String>(4);
                map.put("user", USER);
                map.put("pwd", PWD);
                map.put("srt", STR);
                map.put("cid",CID);
                String url = OPEN_URL+"/save/apis/login";
                // 设置 http 读写超时
                DataExchangeService des = new DataExchangeService(5000, 8000);
                log.info("请求地址:{}",url);
                // 通过 https 方式调用，此方法内部会使用私钥生成签名参数 sign,私钥不会发送
                String res = des.postHttps(url, map);
//                String res="{\"result\":\"ce5a240e-d554-43ad-bd34-5970446a2c75\",\"status\":1001}";
                SinnoiovResult result = JSON.parseObject(res, SinnoiovResult.class);

                if (result.status==1001){
                    String value=result.getResult().toString();
//                    String value="fec2cb4e-c576-4f2e-a3c1-6169f7ce27bd";
                    redisTemplate.opsForValue().set(OPEN_TOKEN,value,1, TimeUnit.DAYS);
                    token=redisTemplate.opsForValue().get(OPEN_TOKEN);
                }

            } catch (Exception e) {
                log.error("e:{}",e.getMessage());
            }
        }
        log.info("返回：{}",token);
        return token.toString();
    }
    /** 一、 车辆最新位置查询（车牌号）接口
     * 本接口提供指定车牌号的车辆最新位置查询。
     91
     * */
    public  ResultOpen<Object> vLastLocationV3(String vclN) {
        try {
            String token=login();
            Map<String, String> map = new HashMap<String, String>(5);
            map.put("token", token);
            map.put("cid", CID);
            map.put("srt", STR);
//            map.put("vclN", "陕YH0008");
            map.put("vclN",vclN);
            map.put("timeNearby", "30");
            String url = OPEN_URL+"/save/apis/vLastLocationV3";
            DataExchangeService des = new DataExchangeService(5000, 8000);
            log.info("请求地址:{}",url);
            // 通过 https 方式调用，此方法内部会使用私钥生成签名参数 sign,私钥不会发送
            String res = des.postHttps(url, map);
            log.info("返回：{}",res);
            return JSON.parseObject(res,ResultOpen.class);
        } catch (Exception e) {
            log.error("e:{}",e.getMessage());
        }
        return null;
    }
    /**
     * 车辆轨迹查询（车牌号）接口
     */
    public ResultOpen<Object> vHisTrack24(String vclN, LocalDateTime qryBtm, long hours){
        try {
            String token=login();
            Map<String, String> map = new HashMap<String, String>(5);
            map.put("token", token);
            map.put("cid", CID);
            map.put("srt", STR);
//            map.put("vclNs", "陕YH0008_1,陕YH0009_2");
            map.put("vclN", vclN);
            String qryBtmStr=DateUtils.formatLocalDateTime(qryBtm);
            map.put("qryBtm",qryBtmStr);
            String qryEtmStr=DateUtils.formatLocalDateTime(qryBtm.plusHours(hours));
            map.put("qryEtm",qryEtmStr);
            ResultOpen<Object> resultOpen=new ResultOpen<>();
            if(LocalDateTime.now().isAfter(qryBtm.plusHours(hours))){

                String url = OPEN_URL+"/save/apis/vHisTrack24";
                DataExchangeService des = new DataExchangeService(5000, 8000);
                log.info("请求地址:{}",url);
                // 通过 https 方式调用，此方法内部会使用私钥生成签名参数 sign,私钥不会发送
                String res = des.postHttps(url, map);
    //            log.info("返回：{}",res);
                resultOpen= JSON.parseObject(res,ResultOpen.class);
            }else {
                resultOpen.setStatus(1002);
                resultOpen.setResult("选择时间段超出了当前时间！请选择正确时间段");
            }

            return resultOpen;
        } catch (Exception e) {
            log.error("vHisTrack24异常--车牌号：{},e:{}",vclN,e.getMessage());
        }
        return null;
    }
    public SinoiovHisTrack apiCoverSiniov(ApiHisTrack apiHisTrack,String recordId){
        double[] coordinates=GPSUtil.coordinatesStrToDou(apiHisTrack.getLat(),apiHisTrack.getLon());
        SinoiovHisTrack hisTrack=BeanConvertUtils.copy(apiHisTrack,SinoiovHisTrack.class,"lat","lon","gtm");
        hisTrack.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
        hisTrack.setRecordId(recordId);
        hisTrack.setLat(BigDecimal.valueOf(coordinates[0]));
        hisTrack.setLon(BigDecimal.valueOf(coordinates[1]));
        hisTrack.setGtm(DateUtils.parseLocalDateTime(apiHisTrack.getGtm(),DateUtils.DATE_TIME_FORMATTER));
        hisTrack.setIsUse(SinoiovHisTrack.USE_YES);
        return hisTrack;
    }
    /**
     * 多辆车辆定位查询
     */
    public void vLastLocationMultiV4(String vclNs){
        try {
            String token=login();
            Map<String, String> map = new HashMap<String, String>(5);
            map.put("token", token);
            map.put("cid", CID);
            map.put("srt", STR);
//            map.put("vclNs", "陕YH0008_1,陕YH0009_2");
            map.put("vclNs", vclNs);
            map.put("timeNearby", "30");
            String url = OPEN_URL+"/save/apis/vLastLocationMultiV4";
            DataExchangeService des = new DataExchangeService(5000, 8000);
            log.info("请求地址:{}",url);
            // 通过 https 方式调用，此方法内部会使用私钥生成签名参数 sign,私钥不会发送
            String res = des.postHttps(url, map);
            log.info("返回：{}",res);
        } catch (Exception e) {
            log.error("e:{}",e.getMessage());
        }
    }

}
